package com.yuanqi.service;

import com.yuanqi.domain.User;
import com.yuanqi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 验证用户登录
     */
    public Optional<User> authenticateUser(String username, String password) {
        log.info("开始验证用户: {}", username);
        
        // 先尝试查找用户（不限制状态）
        Optional<User> userOpt = userRepository.findByUsername(username);
        
        if (userOpt.isEmpty()) {
            log.warn("用户不存在: {}", username);
            return Optional.empty();
        }
        
        User user = userOpt.get();
        log.info("找到用户: {}, 状态: {}, 密码哈希: {}", username, user.getStatus(), user.getPasswordHash());
        
        // 检查用户状态
        if (user.getStatus() == null || user.getStatus() != 1) {
            log.warn("用户状态异常: {}, 状态值: {}", username, user.getStatus());
            return Optional.empty();
        }
        
        // 验证密码
        boolean passwordMatch = passwordEncoder.matches(password, user.getPasswordHash());
        log.info("密码验证结果: {}", passwordMatch);
        
        if (passwordMatch) {
            // 更新最后登录时间
            user.setLastLoginAt(LocalDateTime.now());
            userRepository.save(user);
            log.info("用户登录成功: {}", username);
            return Optional.of(user);
        } else {
            log.warn("密码验证失败: {}", username);
            return Optional.empty();
        }
    }

    /**
     * 根据用户名查找用户
     */
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    /**
     * 创建新用户
     */
    public User createUser(String username, String password, String name) {
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }

        User user = new User();
        user.setUsername(username);
        user.setPasswordHash(passwordEncoder.encode(password));
        user.setName(name);
        user.setStatus((byte) 1); // 启用状态
        user.setIsSuperAdmin((byte) 0); // 非超级管理员
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        return userRepository.save(user);
    }

    /**
     * 加密密码
     */
    public String encodePassword(String rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }
    
    /**
     * 临时方法：生成指定密码的BCrypt哈希（用于调试）
     */
    public String generateHashForPassword(String password) {
        String hash = passwordEncoder.encode(password);
        log.info("密码 '{}' 的BCrypt哈希: {}", password, hash);
        return hash;
    }
    

}
